/** @file    FormBundleManager.cpp
 *  @author  Alessandro Polo
 *  @version $Id: FormBundleManager.cpp 2867 2010-08-07 20:44:51Z alex $
 *  @brief
 * File containing methods for the wosh::gui::FormBundleManager class.
 * The header for this class can be found in FormBundleManager.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include "FormBundleManager.h"
 #include "ui_FormBundleManager.h"
 #include <core/BundleManager.h>
 #include <core/List.h>

 #include <QtGui/QInputDialog>
 #include <QtGui/QMessageBox>


using namespace std;
namespace wosh {
 namespace gui {

 WOSH_REGISTER(wosh::gui::FormBundleManager, "wosh::gui::IWidgetGeneric", 1.0, _static_FormBundleManager )
 WOSH_GUI_MAP(wosh::gui::FormBundleManager, "wosh::BundleManager", 0.0, _static_Map_FormBundleManager )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

FormBundleManager::FormBundleManager(QWidget *parent)
	: IWidgetGeneric(parent) {
	this->m_ui = new Ui::FormBundleManager();
	this->m_ui->setupUi(this);

	IWidgetGeneric::setTargetURI(_BundleManager_URI);
	buildMenus();

	// tab Installed Bundles [0]
	this->m_ui->tableViewBundles->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableViewBundles, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableViewBundles, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableBundlesContextMenuRequested(const QPoint&, const QModelIndex&)) );
	connect(this->m_ui->btnBundleStart, SIGNAL(clicked()), this, SLOT(btnBundleStart_clicked()));
	connect(this->m_ui->btnBundleStop, SIGNAL(clicked()), this, SLOT(btnBundleStop_clicked()));
	connect(this->m_ui->btnBundleLoad, SIGNAL(clicked()), this, SLOT(btnBundleLoad_clicked()));

	// tab Supported Bundles [1]
	this->m_ui->tableViewSupportedBundles->setMethodList(_BundleManager_METHOD_ListSupportedBundles);
	connect(this->m_ui->tableViewSupportedBundles, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
//	this->m_ui->tableViewSupportedBundles->setResizeStretch(0);
//	this->m_ui->tableViewSupportedBundles->setContextMenuPolicy(Qt::CustomContextMenu);
	//connect(this->m_ui->tableViewSupportedBundles, SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(tableViewSupportedBundles_ContextMenu(const QPoint&)) );
	connect(this->m_ui->btnBundleInstall, SIGNAL(clicked()), this, SLOT(btnBundleInstall_clicked()));

 }

FormBundleManager::~FormBundleManager() {
	delete this->m_ui;
 }

void FormBundleManager::changeEvent(QEvent *e) {
	QWidget::changeEvent(e);
	if ( e->type() == QEvent::LanguageChange )
		this->m_ui->retranslateUi(this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBundleManager::refreshAll() {
	this->setWindowTitle( QString("Bundle Manager [%1]").arg(this->getTargetURI().getKernelName().c_str()) );
	this->m_ui->tableViewBundles->refreshData();
	this->m_ui->tableViewSupportedBundles->refreshData();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBundleManager::btnBundleStart_clicked() {
	Variant bundleName = this->m_ui->tableViewBundles->getCurrentItemAsVariantAtCol(0);
	List* args = new List(2);
	args->push_back( bundleName.clone() );
	args->push_back<Variant>( "start" );
	executeRemoteMethod( _BundleManager_METHOD_control_bundle, args );
 }

void FormBundleManager::btnBundleStop_clicked() {
	Variant bundleName = this->m_ui->tableViewBundles->getCurrentItemAsVariantAtCol(0);
	List* args = new List(2);
	args->push_back( bundleName.clone() );
	args->push_back<Variant>( "stop" );
	executeRemoteMethod( _BundleManager_METHOD_control_bundle, args );
 }

void FormBundleManager::btnBundleLoad_clicked() {
	bool ok;
	QString bundlestr = QInputDialog::getText(this, tr("Load Bundle.."), tr("Enter Bundle-Type [optional Bundle-Name]:"), QLineEdit::Normal, "", &ok);
	if ( !ok || bundlestr.isEmpty() )
		return;
	QStringList params = bundlestr.split(" ");
	if ( params.empty() ) return;
	string bundle_type = params.at(0).toLatin1().data();
	string bundle_name = "";
	if ( params.count() > 1 )
		bundle_name = params.at(1).toLatin1().data();
	if ( params.count() > 2 )
		QMessageBox::warning(this, tr("Warning"), tr("Only two parameters are supported.") );

	List* args = List::createFrom<Variant>(bundle_type, bundle_name);
	executeRemoteMethod( _BundleManager_METHOD_LoadBundle, args );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBundleManager::btnBundleInstall_clicked() {
	Variant bundleType = this->m_ui->tableViewSupportedBundles->getCurrentItemAsVariantAtCol(0);
	bool ok;
	QString bundle_name = QInputDialog::getText(this, tr("Load Bundle.."), tr("Enter optional Bundle-Name]:"), QLineEdit::Normal, "", &ok);
	List* args = new List(2);
	args->push_back( bundleType.clone() );
	args->push_back<Variant>( bundle_name.toLatin1().data() );
	executeRemoteMethod( _BundleManager_METHOD_LoadBundle, args );
 }
 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBundleManager::buildMenus() {
	this->menuBundleTitle = new QAction(this);
	this->menuBundleTitle->setEnabled(false);
	this->menuBundleCreateGui = new QAction(this);
	this->menuBundleCreateGui->setText(tr("&Create Gui.."));
	this->menuBundleStart = new QAction(this);
	this->menuBundleStart->setText(tr("&Start.."));
	this->menuBundleStop = new QAction(this);
	this->menuBundleStop->setText(tr("S&top.."));
	this->menuBundle = new QMenu(this);
	this->menuBundle->addAction(this->menuBundleTitle);
	this->menuBundle->addSeparator();
	this->menuBundle->addAction(this->menuBundleStart);
	this->menuBundle->addAction(this->menuBundleStop);
	this->menuBundle->addSeparator();
	this->menuBundle->addAction(this->menuBundleCreateGui);
 }

void FormBundleManager::tableBundlesContextMenuRequested( const QPoint& pos, const QModelIndex& index ) {
	if ( !index.isValid() ) return;
	QPoint globalPos = this->mapToGlobal(pos);
	Variant bundleName = this->m_ui->tableViewBundles->getCurrentItemAsVariantAtCol(0);
	Variant bundleType = this->m_ui->tableViewBundles->getCurrentItemAsVariantAtCol(1);
	Variant bundleState = this->m_ui->tableViewBundles->getCurrentItemAsVariantAtCol(2);

	this->menuBundleTitle->setText( bundleName.toString().c_str() );
	this->menuBundleTitle->setIcon( GuiUtilities::createIconFor(bundleType.toString()) );
	if ( bundleState.toString() == "STARTED" ) {
		this->menuBundleStart->setEnabled(false);
		this->menuBundleStop->setEnabled(true);
	 } else {
		this->menuBundleStart->setEnabled(true);
		this->menuBundleStop->setEnabled(false);
	 }

	QAction* selected = this->menuBundle->exec( globalPos );
	if ( selected == this->menuBundleCreateGui ) {
	
	 }
	else if ( selected == this->menuBundleStart ) {
		List* args = new List(2);
		args->push_back( bundleName.clone() );
		args->push_back<Variant>( "start" );
		executeRemoteMethod( _BundleManager_METHOD_control_bundle, args );
	 }
	else if ( selected == this->menuBundleStop ) {
		List* args = new List(2);
		args->push_back( bundleName.clone() );
		args->push_back<Variant>( "stop" );
		executeRemoteMethod( _BundleManager_METHOD_control_bundle, args );
	 }
 }
 
/*
void FormBundleManager::tableViewSupportedBundles_ContextMenu( const QPoint& pos ) {
	QPoint globalPos = this->mapToGlobal(pos);
	QModelIndex index = this->m_ui->tableViewSupportedBundles->indexAt(pos);
	if ( !index.isValid() )
		return;
	Variant bundleType = this->m_ui->tableViewSupportedBundles->getCurrentItemAsVariantAtCol(0);

	this->menuBundleTitle->setText( bundleType.toString().c_str() );
	this->menuBundleTitle->setIcon( GuiUtilities::createIconFor(bundleType.toString()) );

	QAction* selected = this->menuBundle->exec( globalPos );
	if ( selected == this->menuBundleCreateGui ) {
	 }
 }
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBundleManager::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() || !message.getContent()->isResponse() ) return;
	if ( !isMessageForMeOrFromTarget(message) ) return;
	const wosh::Response* response = message.getContent()->asResponse();

	this->m_ui->tableViewBundles->evalResponse(response);
	this->m_ui->tableViewSupportedBundles->evalResponse(response);

	promptMethodResponse( message, false );

	if ( response->getMethod() == _BundleManager_METHOD_control_bundle && WSUCCEEDED(response->getReturnValue()) ) {
		this->m_ui->tableViewBundles->refreshData();
	 }
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
